<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: Object,
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})

const echartsContainer = ref(null)
let chartInstance = null
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  chartInstance = echarts.init(echartsContainer.value)
  chartInstance.setOption(props.option)
  // 监听窗口大小变化
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  // 清理组件卸载时的事件监听和图表实例
  window.removeEventListener('resize', resizeChart)
  chartInstance && chartInstance.dispose()
})

// 监听option变化重新设置图表
watch(
  () => props.option,
  (newOption) => {
    if (chartInstance) {
      chartInstance.setOption(newOption)
    }
  },
  { deep: true }
)
</script>
<template>
  <div ref="echartsContainer" :style="{ width, height }"></div>
</template>
<style scoped>
/* 样式可以根据需要添加 */
</style>
